package chapter01;

public class Atoi {
    public static int myAtoi(String s) {
        int sum=0,i,j,flag=1;
        char[] toChar=s.toCharArray();
        if(toChar.length<2){
            if(toChar[0]>='0'&&toChar[0]<='9'){
                sum=sum+toChar[0]-'0';
            }
            return sum;
        }
        for(i=1;i<toChar.length;i++){
            if(toChar[0]==' '){
                if(toChar[i-1]==' '&&toChar[i]!=' '){
                    if(toChar[i]=='+'){

                    }else if(toChar[i]=='-'){
                        flag=-flag;
                    }else if(toChar[i]>='0'&&toChar[i]<='9'){
                        sum=sum*10+toChar[i]-'0';
                    }else{
                        return sum*flag;
                    }
                    break;
                }
            }else{
                if(toChar[0]=='+'){

                }else if(toChar[0]=='-'){
                    flag=-flag;
                }else if(toChar[0]>='0'&&toChar[0]<='9'){
                    sum=sum*10+toChar[0]-'0';
                }else{
                    return sum*flag;
                }
                i--;
                break;
            }
        }
        sum=sum*flag;
        for(i++;i<toChar.length;i++){
            if(flag>0){
                if(toChar[i]>='0'&&toChar[i]<='9'){
                    if(sum>Integer.MAX_VALUE/10||sum==Integer.MAX_VALUE/10&&(toChar[i]-'0')>Integer.MAX_VALUE%10){
                        return Integer.MAX_VALUE;
                    }else{
                        sum=sum*10+toChar[i]-'0';
                    }
                }else{
                    break;
                }
            }else{
                if(toChar[i]>='0'&&toChar[i]<='9'){
                    if(sum<Integer.MIN_VALUE/10||sum==Integer.MIN_VALUE/10&&(toChar[i]-'0')>Integer.MIN_VALUE%10*flag){
                        return Integer.MIN_VALUE;
                    }else{
                        sum=sum*10+(toChar[i]-'0')*flag;
                    }
                }else{
                    break;
                }
            }
        }
        return sum;
    }

    public static void main(String[] args) {
        System.out.println(myAtoi("-2147483647"));
    }
}
